/*
 * Copyright (c) 2015 Razeware LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

import CoreData
import UIKit

class DebugViewController: UIViewController {
//    var coreDataStack: CoreDataStack!

    @IBOutlet var exportButton: UIButton!
    @IBOutlet var activityIndicator: UIActivityIndicatorView!

    @IBAction func exportTapped(sender: AnyObject) {
        activityIndicator.startAnimating()
        exportButton.isEnabled = false

        let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
        childContext.parent = CoreDataStack.share.managedObjectContext

        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Device")

        childContext.perform {
            do {
                if let results = try childContext.fetch(fetchRequest) as? [Device] {
                    for device in results {
                        print("Device \(device.name) \(String(describing: device.deviceType?.name))")
                    }
                }
            } catch {
                print("Error fetching records for export")
            }

            DispatchQueue.main.async {
                self.activityIndicator.stopAnimating()
                self.exportButton.isEnabled = true
            }
        }
    }

    
    @IBAction func unassignAllTapped(sender: AnyObject) {
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Device")
        fetchRequest.predicate = NSPredicate(format: "owner != nil")

        do {
            if let results = try CoreDataStack.share.managedObjectContext.fetch(fetchRequest) as? [Device] {
                for device in results {
                    device.owner = nil
                }

                CoreDataStack.share.saveMainContext()

                let alert = UIAlertController(title: "Batch Update Succeeded", message: "\(results.count) devices unassigned.", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                present(alert, animated: true, completion: nil)
            }
        } catch {
            let alert = UIAlertController(title: "Batch Update Failed", message: "There was an error unassigning the devices.", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
            present(alert, animated: true, completion: nil)
        }
    }

    @IBAction func deleteAllTapped(sender: Any?) {
        let deviceTypeFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "DeviceType")
        let deviceTypeDeleteRequest = NSBatchDeleteRequest(fetchRequest: deviceTypeFetchRequest)
        deviceTypeDeleteRequest.resultType = .resultTypeCount

        let deviceFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Device")
        let deviceDeleteRequest = NSBatchDeleteRequest(fetchRequest: deviceFetchRequest)
        deviceDeleteRequest.resultType = .resultTypeCount

        let personFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
        let personDeleteRequest = NSBatchDeleteRequest(fetchRequest: personFetchRequest)
        personDeleteRequest.resultType = .resultTypeCount

        do {
            let deviceTypeResult = try CoreDataStack.share.managedObjectContext.execute(deviceTypeDeleteRequest) as! NSBatchDeleteResult
            let personResult = try CoreDataStack.share.managedObjectContext.execute(personDeleteRequest) as! NSBatchDeleteResult
            let deviceResult = try CoreDataStack.share.managedObjectContext.execute(deviceDeleteRequest) as! NSBatchDeleteResult

            let alert = UIAlertController(title: "Batch Delete Succeeded", message: "\(deviceTypeResult.result!) device type records and \(deviceResult.result!) device records and \(personResult.result!) person records deleted.", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
            present(alert, animated: true, completion: nil)
        } catch {
            let alert = UIAlertController(title: "Batch Delete Failed", message: "There was an error with the batch delete. \(error)", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
            present(alert, animated: true, completion: nil)
        }
    }
}
